<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生姓名" prop="stuName">
        <el-input v-model="queryParams.stuName" placeholder="请输入学号或学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="天数" prop="duration">
        <el-input v-model="queryParams.duration" placeholder="请输入天数" clearable @keyup.enter.native="handleQuery"
          oninput="value=value.replace(/[^\d]/g,'')" :maxlength="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['backend:leave:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="申请人" align="center" prop="stuName" />
      <el-table-column label="学号" align="center" prop="sno" />
      <el-table-column label="假期类别" align="center" prop="leaveType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.parentLevelId != null" type="warning">延假</el-tag>
          <el-tag v-else>请假</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="请假类型" align="center" prop="leaveType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.leave_types" :value="scope.row.leaveType" />
        </template>
      </el-table-column>
      <el-table-column label="天数" align="center" prop="duration">
        <template slot-scope="scope">
          <span>{{ scope.row.duration / 10 + '天' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.leave_audit" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="上位审核人" align="center" prop="auditName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="user.admin == true">
            <el-button size="mini" type="text" icon="el-icon-search" @click="handleXq(scope.row)">详情</el-button>
          </div>
          <div v-else>
            <el-button size="mini" type="text" icon="el-icon-search" @click="handleXq(scope.row)">详情</el-button>
            <el-button v-if="scope.row.status == 1" size="mini" type="text" icon="el-icon-edit"
              @click="handleUpdate(scope.row)" v-hasPermi="['backend:leave:edit']">审核</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改请假申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <div v-if="form.parentLevelId == null">
          <el-descriptions title="" direction="vertical" :column="5" border style="margin-bottom:20px;">
            <el-descriptions-item label="学生姓名" :span="2">{{ form.stuName }}</el-descriptions-item>
            <el-descriptions-item label="学号" :span="1">{{ form.sno }}</el-descriptions-item>
            <el-descriptions-item label="假期类别">
              <el-tag v-if="form.parentLevelId != null"  type="warning">延假</el-tag>
              <el-tag v-else>请假</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="请假类型">
              <dict-tag :options="dict.type.leave_types" :value="form.leaveType" />
            </el-descriptions-item>
            <el-descriptions-item label="开始时间" :span="2">{{ form.beginTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间" :span="1">{{ form.endTime }}</el-descriptions-item>
            <el-descriptions-item label="累计天数" :span="2">{{ form.duration / 10 }}天</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="5">{{ form.cause }}</el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-if="fileS != null">
              <el-image v-for="(item, index) in fileS" :key="index" :src="imgUrl(item.path)" fit="cover"
                style="width: 23%; height: 200px;  margin-left:1%;margin-right: 1%;"
                :preview-src-list="[imgUrl(item.path)]" disabled />
            </el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-else>
              无图片
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-else>
          <el-descriptions title="" direction="vertical" :column="5" border style="margin-bottom:20px;">
            <el-descriptions-item label="学生姓名" :span="2">{{ form.stuName }}</el-descriptions-item>
            <el-descriptions-item label="学号" :span="1">{{ form.sno }}</el-descriptions-item>
            <el-descriptions-item label="假期类别">
              <el-tag v-if="form.parentLevelId != null" type="warning">延假</el-tag>
              <el-tag v-else>请假</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="请假类型">
              <dict-tag :options="dict.type.leave_types" :value="form.leaveType" />
            </el-descriptions-item>
            <el-descriptions-item label="开始时间" :span="2">{{ form.beginTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间" :span="1">{{ form.endTime }}</el-descriptions-item>
            <el-descriptions-item label="累计天数" :span="2">{{ form.duration }}天</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="5">{{ form.cause }}</el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-if="fileS != null">
              <el-image v-for="(item, index) in fileS" :key="index" :src="imgUrl(item.path)" fit="cover"
                style="width: 23%; height: 200px;  margin-left:1%;margin-right: 1%;"
                :preview-src-list="[imgUrl(item.path)]" disabled />
            </el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-else>
              无图片
            </el-descriptions-item>
          </el-descriptions>

          <h3>历史申请</h3>
          <el-tabs tab-position="left">
            <el-tab-pane v-for="(item, index) in oldLeaveInfo" :key="index"
              :label="parseTime(item.beginTime, '{y}-{m}-{d}')">
              <el-descriptions title="" direction="horizontal" :column="4" border>
                <el-descriptions-item label="假期类别" :span="4">
                  <el-tag v-if="item.parentLevelId != null" type="warning"> 延假 </el-tag>
                  <el-tag v-else>请假</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="请假类型" :span="4">
                  <dict-tag :options="dict.type.leave_types" :value="item.leaveType" />
                </el-descriptions-item>
                <el-descriptions-item label="审核状态" :span="2">
                  <dict-tag :options="dict.type.leave_audit" :value="item.status" />
                </el-descriptions-item>
                <el-descriptions-item label="假期状态" :span="2">
                  <dict-tag :options="dict.type.vacation_status" :value="item.vacationStatus"
                    v-if="item.vacationStatus != null" />
                  <el-tag v-else>审核中</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="开始时间" :span="2">{{ item.beginTime }}</el-descriptions-item>
                <el-descriptions-item label="结束时间" :span="2">{{ item.endTime }}</el-descriptions-item>
                <el-descriptions-item label="累计天数" :span="4">{{ item.duration / 10 }}天</el-descriptions-item>

                <el-descriptions-item label="申请原因" :span="4">{{ item.cause }}</el-descriptions-item>
              </el-descriptions>

            </el-tab-pane>
          </el-tabs>
        </div>

        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="form.status" size="medium">
            <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.value" :disabled="item.disabled">{{
              item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="更换流程" prop="process" v-if="form.status == 2">
          <el-radio-group v-model="form.process" size="medium">
            <el-radio v-for="(item, index) in processOptions" :key="index" :label="item.value"
              :disabled="item.disabled">{{ item.label }}</el-radio>
          </el-radio-group>
          <div>
            若当前学生的假期申请需要调换部门审核 请选择是
          </div>
        </el-form-item>

        <el-form-item label="审核部门" prop="auditDp" v-if="form.process == 1">
          <el-radio-group v-model="form.auditDp" size="medium">
            <el-radio v-for="(item, index) in auditDpOptions" :key="index" :label="item.deptId"
              :disabled="item.disabled">{{ item.deptName }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审批意见" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入审批意见" :autosize="{ minRows: 4, maxRows: 4 }"
            :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="title" :visible.sync="xqOpen" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        
        <div v-if="form.parentLevelId == null">
        <el-descriptions title="" direction="vertical" :column="5" border>
          <el-descriptions-item label="学生姓名" :span="2">{{ form.stuName }}</el-descriptions-item>
          <el-descriptions-item label="学号" :span="1">{{ form.sno }}</el-descriptions-item>
          <el-descriptions-item label="假期类别">
            <el-tag v-if="form.parentLevelId != null" type="warning">延假</el-tag>
            <el-tag v-else>请假</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请假类型">
            <dict-tag :options="dict.type.leave_types" :value="form.leaveType" />
          </el-descriptions-item>
          <el-descriptions-item label="开始时间" :span="1">{{ form.beginTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间" :span="1">{{ form.endTime }}</el-descriptions-item>
          <el-descriptions-item label="累计天数" :span="1">{{ form.duration / 10 }}天</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <dict-tag :options="dict.type.leave_audit" :value="form.status" />
          </el-descriptions-item>
          <el-descriptions-item label="假期状态">
            <dict-tag :options="dict.type.vacation_status" :value="form.vacationStatus"
              v-if="form.vacationStatus != null" />
            <el-tag v-else>审核中</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="5">{{ form.cause }}</el-descriptions-item>
          <el-descriptions-item label="图片" :span="5" v-if="fileS != null">
            <el-image v-for="(item, index) in fileS" :key="index" :src="imgUrl(item.path)" fit="cover"
              style="width: 23%; height: 200px;  margin-left:1%;margin-right: 1%;" :preview-src-list="[imgUrl(item.path)]"
              disabled />
          </el-descriptions-item>
          <el-descriptions-item label="图片" :span="5" v-else>
            无图片
          </el-descriptions-item>
        </el-descriptions>
        </div>
        <div v-else>
          <el-descriptions title="" direction="vertical" :column="5" border style="margin-bottom:20px;">
            <el-descriptions-item label="学生姓名" :span="2">{{ form.stuName }}</el-descriptions-item>
            <el-descriptions-item label="学号" :span="1">{{ form.sno }}</el-descriptions-item>
            <el-descriptions-item label="请假类型">
              <dict-tag :options="dict.type.leave_types" :value="form.leaveType" />
            </el-descriptions-item>
            <el-descriptions-item label="假期类别">
              <el-tag v-if="form.parentLevelId != null">延假</el-tag>
              <el-tag v-else type="info">无类别</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="开始时间" :span="2">{{ form.beginTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间" :span="1">{{ form.endTime }}</el-descriptions-item>
            <el-descriptions-item label="累计天数" :span="2">{{ form.duration }}天</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="5">{{ form.cause }}</el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-if="fileS != null">
              <el-image v-for="(item, index) in fileS" :key="index" :src="imgUrl(item.path)" fit="cover"
                style="width: 23%; height: 200px;  margin-left:1%;margin-right: 1%;"
                :preview-src-list="[imgUrl(item.path)]" disabled />
            </el-descriptions-item>
            <el-descriptions-item label="图片" :span="5" v-else>
              无图片
            </el-descriptions-item>
          </el-descriptions>

          <h3>历史申请</h3>
          <el-tabs tab-position="left">
            <el-tab-pane v-for="(item, index) in oldLeaveInfo" :key="index"
              :label="parseTime(item.beginTime, '{y}-{m}-{d}')">
              <el-descriptions title="" direction="horizontal" :column="4" border>
                <el-descriptions-item label="请假类型" :span="4">
                  <dict-tag :options="dict.type.leave_types" :value="item.leaveType" />
                </el-descriptions-item>
                <el-descriptions-item label="假期类别" :span="4">
                  <el-tag v-if="item.parentLevelId != null"> 延假 </el-tag>
                  <el-tag v-else type="info">无类别</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="审核状态" :span="2">
                  <dict-tag :options="dict.type.leave_audit" :value="item.status" />
                </el-descriptions-item>
                <el-descriptions-item label="假期状态" :span="2">
                  <dict-tag :options="dict.type.vacation_status" :value="item.vacationStatus"
                    v-if="item.vacationStatus != null" />
                  <el-tag v-else>审核中</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="开始时间" :span="2">{{ item.beginTime }}</el-descriptions-item>
                <el-descriptions-item label="结束时间" :span="2">{{ item.endTime }}</el-descriptions-item>
                <el-descriptions-item label="累计天数" :span="4">{{ item.duration / 10 }}天</el-descriptions-item>

                <el-descriptions-item label="申请原因" :span="4">{{ item.cause }}</el-descriptions-item>
              </el-descriptions>

            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 历史审核 -->
        <el-form-item label="审核记录" style="margin-top:20px" v-if="auditInfo.length != 0">
          <el-timeline>
            <el-timeline-item v-for="(item, index) in auditInfo" :key="index"
              :timestamp="parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}')" placement="top">
              <el-card>
                <!-- <h4>审核部门：{{ item.stName }}</h4> -->
                <p>审核人：{{ item.auditName }}</p>
                <p>审核状态：
                  <el-tag v-if="item.status == 1">审核中</el-tag>
                  <el-tag v-if="item.status == 2" type="success">通过</el-tag>
                  <el-tag v-if="item.status == 3" type="danger">不通过</el-tag>
                </p>
                <p>审批意见:{{ item.reason }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <!-- <el-button @click="xqClose">取消</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeave, delLeave, auditLeave, listOldLeave } from "@/api/backend/leave";
import { listLeaveDep } from "@/api/system/dept";
import { findListAuditLeave } from "@/api/backend/auditLeave";
import { getSessionStorage } from '@/utils/auth'
import { getListResources } from "@/api/backend/fileResources";

export default {
  name: "Leave",
  dicts: ['leave_types', 'leave_audit', 'vacation_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假申请表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      xqOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuName: null,
        duration: null,
      },
      fileS: null,
      // 表单参数
      form: {
        duration: null,
      },
      oldLeaveInfo: {},
      auditInfo: {},
      user: {},
      // 表单校验
      rules: {
        process: [{
          required: true,
          message: '更换流程不能为空',
          trigger: 'change'
        }],
        auditDp: [{
          required: true,
          message: '审核部门不能为空',
          trigger: 'change'
        }],
        status: [{
          required: true,
          message: '审核状态不能为空',
          trigger: 'change'
        }],
        reason: [{
          required: true,
          message: '请输入审批意见',
          trigger: 'blur'
        }],
      },
      processOptions: [{
        "label": "是",
        "value": 1
      }, {
        "label": "否",
        "value": 2
      }],
      auditDpOptions: [],
      statusOptions: [{
        "label": "通过",
        "value": 2
      }, {
        "label": "不通过",
        "value": 3
      }],
    };
  },
  created() {
    this.getlistLeaveDep();
    this.getList();
    this.user = getSessionStorage();
  },
  methods: {
    imgUrl(path) {
      return process.env.VUE_APP_BASE_API + path;
    },
    getlistLeaveDep() {
      listLeaveDep().then(response => {
        this.auditDpOptions = response.data;
      });
    },
    /** 查询请假申请列表 */
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stu: null,
        beginTime: null,
        endTime: null,
        cause: null,
        duration: null,
        fileId: null,
        audit: null,
        auditLevel: null,
        auditNewLevel: null,
        status: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加请假申请";
    },
    /**  获取图片信息  */
    getImgInfos(fileIds) {
      if (fileIds != null && fileIds != "" && fileIds != "undefined") {
        var Info = {
          fileIds: fileIds
        }
        getListResources(Info).then(response => {
          this.fileS = response.rows;
        });
      }
    },
    handleXq(row) {
      this.reset();
      this.fileS = null;
      // console.log(row.fileIds.split(','))
      this.getImgInfos(row.fileIds);
      this.form = JSON.parse(JSON.stringify(row));
      let data = {
        applyLeaveId: row.id
      }
      findListAuditLeave(data).then(response => {
        if (this.form.parentLevelId != null) {
          var data = {
            Id: this.form.parentLevelId
          }
          listOldLeave(data).then(response => {
            this.oldLeaveInfo = response.rows;
            this.form.beginTime = response.rows[0].beginTime;
            let time = new Date(this.form.endTime).getTime() - new Date(this.form.beginTime).getTime();
            let day = Math.floor(time / (24 * 60 * 60 * 1000)); // 计算天数
            let hour = Math.floor((time % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));// 计算小时数
            if (hour == 0) {
              this.form.duration = day;
            } else if (hour <= 12) {
              this.form.duration = day + 0.5;
            } else {
              this.form.duration = day + 1;
            }
          });
        }
        this.auditInfo = response.rows;
        this.title = "审核详情";
        this.xqOpen = true;
      });
    },
    xqClose() {
      this.xqOpen = false;
      this.fileS = null;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fileS = null;
      this.getImgInfos(row.fileIds);
      this.form = JSON.parse(JSON.stringify(row));
      this.$set(this.form, 'process', 2)
      this.$set(this.form, 'status', 2)
      if (this.form.parentLevelId != null) {
        var data = {
          Id: this.form.parentLevelId
        }
        listOldLeave(data).then(response => {
          this.oldLeaveInfo = response.rows;
          this.form.beginTime = response.rows[0].beginTime;
          let time = new Date(this.form.endTime).getTime() - new Date(this.form.beginTime).getTime();
          let day = Math.floor(time / (24 * 60 * 60 * 1000)); // 计算天数
          let hour = Math.floor((time % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));// 计算小时数
          if (hour == 0) {
            this.form.duration = day;
          } else if (hour <= 12) {
            this.form.duration = day + 0.5;
          } else {
            this.form.duration = day + 1;
          }
        });

      }
      this.open = true;
      this.title = "审核假期";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            auditLeave(this.form).then(response => {
              this.$modal.msgSuccess("审核成功!");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除请假申请编号为"' + ids + '"的数据项？').then(function () {
        return delLeave(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backend/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>